package com.itheima.反射.homework.demo02;

import java.lang.reflect.Method;
import java.util.HashMap;


/**
 * @Author 王加鑫
 * @Date 2021/5/26 19:21
 * @Version 1.0
 * 2、【编号2406】现获取到一个Map集合，集合中以属性名称对应属性值的方式存放了一个学生对象的信息，如下：
 * HashMap<String, Object> map = new HashMap<>();
 * map.put("id", "heima001");
 * map.put("name", "张三");
 * map.put("age", 23);
 * map.put("birthday", "1999-09-09");
 * 这些信息与学生类（Student）中的属性一一对应
 * class Student {
 *     private String id;
 *     private String name;
 *     private Integer age;
 *     private String birthday;
 *
 *     // getters and setters...
 *     // toString()...
 * }
 * 请利用反射的知识，将集合中的属性值通过学生实体类的set方法，封装到一个学生对象中，并打印该对象展示。
 */
public class Demo02 {
    public static void main(String[] args) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", "heima001");
        map.put("name", "张三");
        map.put("age", 23);
        map.put("birthday", "1999-09-09");

        Class<Student> studentClass = Student.class;
        Student student = studentClass.getConstructor().newInstance();
        Method[] methods = studentClass.getMethods();
        for (String s : map.keySet()) {
            //将获取到的key第一个字符大写
            char c = s.toUpperCase().charAt(0);
            for (Method method : methods) {
                //拼接字符 拼出 setId
                if(method.getName().equals("set" + c + s.substring(1))){
                    method.invoke(student,map.get(s));
                }
            }
        }
        System.out.println(student);
    }
}

class Student{
    private String id;
    private String name;
    private Integer age;
    private String birthday;

    public Student() {
    }

    public Student(String id, String name, Integer age, String birthday) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}
